# -*- coding: utf-8 -*-

## ------------------------------------------------------------
## Copyright 2010 Pierre-Antoine Delsart
## 
## This file is part of LeVin.
## 
## LeVin is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
## 
## LeVin is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
## You should have received a copy of the GNU General Public License
## along with LeVin.  If not, see <http://www.gnu.org/licenses/>.
## ---------------------------------------------------------------


from PythonQt import QtCore, QtGui,QtSvg
import qtcommon
import tabcomponent
from qtcommon import tr, WinePixmaps, getIcon, getData,connect
from wineAreas import wineWorld , wineColors
import editWine

class WineDescElt(object):
    """WinDescElt hold some widgets describing parts of a wine.
    It provides an interface to update the contained widgets from a given wine : update(w)

    Most of the time the constructor takes as argument
     - a parent widget
     - an attribute string : the wine attribute to display in the widget(s)
    """ 
    def update(self,b):
        pass
class WineDescLabel(WineDescElt):
    def __init__(self, att, parent ,desc=''):
        self.qtelt = QtGui.QLabel( parent)
        self.qtelt.setToolTip(  desc )
        self.qtelt.setObjectName( 'Desc_'+att)
        self.qtelt.setWordWrap(True)
        self.att = att
        self.desc = desc
    def update(self, bott):
        a = getattr(bott , self.att)
        #print 'WineDescLabel ',a
        if a : self.qtelt.setText( a )
        self.qtelt.setToolTip( self.desc )        
class WineDescLocalisation(WineDescElt):
    def __init__(self,  parent ):
        self.qtelt = QtGui.QLabel( parent)
    def update(self, bott):
        a1 = bott.country
        a2 = bott.region
        self.qtelt.setText( a1 +' , '+a2+'     '+wineColors[bott.color] )

class WineDescInFormLayout(WineDescElt):
    """The describing widgets are inserted in a FormLayout : the formLAyout must be given in the ctor. """
    descType = QtGui.QLabel
    def __init__(self, att, parent, formLayout , desc):
        self.labElt = QtGui.QLabel( parent)
        self.labElt.setObjectName( 'Lablayout')
        self.descElt = self.descType( parent)
        self.descElt.setObjectName( 'Desclayout')
        self.labElt.setText( desc )
        formLayout.setWidget(formLayout.N, QtGui.QFormLayout.LabelRole, self.labElt)
        formLayout.setWidget(formLayout.N, QtGui.QFormLayout.FieldRole, self.descElt)
        formLayout.N +=1
        self.att = att
        if self.descType == QtGui.QLabel:
            self.descElt.setWordWrap(True) # avoid label size increase (thus avoid changing the splitter)
    def update(self, bott):
        a = getattr(bott , self.att)
        self.descElt.setText( unicode(a) if a is not None else '')

class WineTextInFormLayout(WineDescInFormLayout):
    """ same as above except the describing widget is a QTextBrowser instead of a QLabel"""
    descType = QtGui.QTextBrowser
    def __init__(self, att, parent, formLayout , desc):
        WineDescInFormLayout.__init__(self, att, parent, formLayout , desc)
        #self.descElt.setReadOnly(True)
        self.descElt.setOpenExternalLinks(True)

    def update(self, bott):
        a = getattr(bott , self.att)
        #self.descElt.clear()
        self.descElt.setHtml( a if a else '')
        #self.descElt.setPlainText( a if a else '')
        #self.descElt.setHtml(self.descElt.toHtml() )

class WineOptimalInFormLayout(WineDescInFormLayout):
    """Dedicated to describe optimal age of a wine. """
    def __init__(self, parent, formLayout ):
        WineDescInFormLayout.__init__(self, "", parent, formLayout , tr("Optimal in"))
    
    def update(self, bott):
        max = getattr(bott , "optimalMax")
        min = getattr(bott , "optimalMin")
        if max and min :
            self.descElt.setText( tr("%1 to %2").arg(min).arg(max) )
        else:
            self.descElt.setText( " ? " )

class WineDescRating(WineDescElt):
    def __init__(self, parent ):
        #self.qtelt = QtGui.QFrame( parent )
        hlayout = QtGui.QVBoxLayout( parent )
        hlayout.setAlignment(QtCore.Qt.AlignCenter)
        #self.qtelts = [QtSvg.QSvgWidget( parent ) for i in range(12) ]
        self.qtelts = [qtcommon.FixedWidthSVG( parent ) for i in range(12) ]
        for q in self.qtelts:
            q.setObjectName( 'Desc_meanrate')
            #q.setMinimumHeight(40)
            #q.setMinimumWidth(250)            
            q.setVisible(False)
            hlayout.addWidget(q)
        #self.qtelt.setScaledContents(True)
        self.att = "meanrate"
        self.hlayout = hlayout
        self.currentWidget = self.qtelts[-1]

    def update(self, bott):
        a = getattr(bott , self.att)
        a = int(a) if a is not None else -1
        newW = self.qtelts[a]
        self.currentWidget.setVisible(False)
        newW.setVisible(True)
        self.currentWidget = newW
            

    def setupPixmaps(self):
        h=30
        svgWid = self.qtelts
        svgWid[-1].load(getIcon("noratePic.svg"))
        for i,w in enumerate(svgWid[:-1]):
            w.load(getIcon("ratingGlass"+str(i)+'.svg'))
            w.setToolTip(str(i)+"/10")




class WineDescriptionTab(tabcomponent.TabComponent):
    """The component describing a wine in a tab of the gui. """

    def setupTab(self, tabWidget):
        self.bottleDialog = editWine.getEditWineUI()
        
        wineTab = QtGui.QWidget()
        wineTab.setObjectName("winetab")

        verticalLayoutDesc = QtGui.QVBoxLayout(wineTab)
        verticalLayoutDesc.setSpacing(20)
        verticalLayoutDesc.setObjectName("verticalLayoutDesc")
        self.verticalLayoutDesc = verticalLayoutDesc

        def addToVLayout( w , membername, vbox = verticalLayoutDesc):
            setattr(self,membername, w)
            vbox.addWidget( w.qtelt )
            return w
        

        self.formLayoutDesc = QtGui.QFormLayout()
        self.formLayoutDesc.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow)
        self.formLayoutDesc.setVerticalSpacing(13)
        self.formLayoutDesc.N = 0

        wineDescElts = []
        wineDescElts.append( addToVLayout( WineDescLocalisation(wineTab ) , "localDescElt" ) )

        wineNameBox = QtGui.QFrame(wineTab)
        wineNameBoxLay = QtGui.QVBoxLayout(wineNameBox)
        wineNameBox.setObjectName("wineNameBox")
        self.wineNameBox = wineNameBox
        wineNameBox.setLayout( wineNameBoxLay)
        verticalLayoutDesc.addWidget(wineNameBox)
        wineDescElts.append( addToVLayout( WineDescLabel( "appellation", wineNameBox , tr( "Appellation" ) ) ,"appelDescElt", vbox=wineNameBoxLay) )
        wineDescElts.append( addToVLayout( WineDescLabel( "cru_name", wineNameBox, tr( "Vintage Name" ) ), "cruDescElt" ,vbox=wineNameBoxLay) )
        wineDescElts.append( addToVLayout( WineDescLabel( "millesime", wineNameBox, tr( "Vintage year" ) ), "millesimeDescElt" ,vbox=wineNameBoxLay) )


        spacerItem = QtGui.QSpacerItem(20, 109, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        verticalLayoutDesc.addItem( spacerItem )
        self.rateDescElt = WineDescRating( wineTab) 
        wineDescElts.append( self.rateDescElt  )
        verticalLayoutDesc.addLayout( self.rateDescElt.hlayout )            

        spacerItem = QtGui.QSpacerItem(20, 109, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        verticalLayoutDesc.addItem( spacerItem )
        
        wineDescElts.append( WineDescInFormLayout("cepage",wineTab, self.formLayoutDesc, tr( "Grape variety" )) )
        wineDescElts.append( WineOptimalInFormLayout(wineTab, self.formLayoutDesc )        )
        wineDescElts.append( WineDescInFormLayout("acquireComment",wineTab, self.formLayoutDesc, tr( "Acquire" )) )
        wineDescElts.append( WineDescInFormLayout("numInStock",wineTab, self.formLayoutDesc, tr( "Bottles" )) )
        wineDescElts.append( WineDescInFormLayout("pricePerBottle",wineTab, self.formLayoutDesc, tr( "Price" )) )        
        wineDescElts.append( WineDescInFormLayout("productor",wineTab, self.formLayoutDesc, tr( "Productor" )) )
        wineDescElts.append( WineTextInFormLayout("otherInfo",wineTab, self.formLayoutDesc, tr( "Description" )) )

        self.textb = wineDescElts[-1]
        
        verticalLayoutDesc.addLayout( self.formLayoutDesc )            

        spacerItem = QtGui.QSpacerItem(20, 109, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        verticalLayoutDesc.addItem( spacerItem )


        self.verticalLayoutDesc = verticalLayoutDesc

        self.setupEditButtonBox() # in this class only because this tab is the default tab



        
        tabWidget.addTab(wineTab, tr("Details"))
        self.tabId = tabWidget.indexOf(wineTab)
        #self.tabId = tabWidget.currentIndex()
        self.wineTab = wineTab

        self.wineDescElts = wineDescElts        


    def update(self,b):
        for v in self.wineDescElts:
            v.update(b)

    def retranslate(self):
        self.rateDescElt.setupPixmaps()        
        self.alignLabels()


        
    def connect(self):
        tabcomponent.TabComponent.connect(self)
        mainWindow = self.mainWindow

    def alignLabels(self):
        labels = [self.appelDescElt.qtelt,
                  self.cruDescElt.qtelt,
                  self.millesimeDescElt.qtelt,              
                  #ui.rateDescElt.qtelt,
                  ]
        for l in labels :
            l.setAlignment(QtCore.Qt.AlignCenter)

